﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Models.ICModels;
using Casamiel.API.Application.Services;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.Application;
using Casamiel.Common.Utilities;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using Casamiel.Common;
using Casamiel.Domain.Response;
using Casamiel.Domain.Request.IC;
using Enyim.Caching;
using Casamiel.API.Application;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers.V2
{
    /// <summary>
    /// Booking controller.
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("2.0")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
    [EnableCors("any")]
    [TypeFilterAttribute(typeof(BookingCheckTokenAttribute))]
    [ApiController]
    public class BookingController : BaseController
    {
        private readonly IMemcachedClient _memcachedClient;
        private readonly string _memcachedPre = "";
        private readonly string _imgUrl = "";
        private readonly NLog.ILogger logger = NLog.LogManager.GetLogger("BookingService");
        private readonly IIcApiService _icApiService;
        private readonly IEmployeeService _employeeService;
        //private readonly IMemberService _memberService;
        private readonly IUserLogService _userLog;
        private readonly ICacheService _cacheService;
        private readonly IMobileCheckCode _mobileCheckCode;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="snapshot"></param>
        /// <param name="memcachedClient"></param>
        /// <param name="employeeService">Employee service.</param>
        /// <param name="userLog">User log.</param>
        /// <param name="cacheService">Cache service.</param>
        /// <param name="mobileCheckCode">Mobile check code.</param>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="settings"></param>
        public BookingController(IOptionsSnapshot<CasamielSettings> snapshot, IMemcachedClient memcachedClient, IEmployeeService employeeService,  IUserLogService userLog, ICacheService cacheService,
                                  IMobileCheckCode mobileCheckCode, IIcApiService iicApiService, IOptionsSnapshot<IcServiceSettings> settings)
        {
            if (snapshot == null) {
                throw new ArgumentNullException(nameof(snapshot));
            }

            if (settings == null) {
                throw new ArgumentNullException(nameof(settings));
            }
            _memcachedClient = memcachedClient;
            _employeeService = employeeService;
            // _memberService = memberService;
            _userLog = userLog;
            _cacheService = cacheService;
            _mobileCheckCode = mobileCheckCode;
            _icApiService = iicApiService;
            _memcachedPre = snapshot.Value.MemcachedPre;
            _imgUrl = settings.Value.appUrls[0].Url;
        }
        /// <summary>
        /// Basedataquery the specified data and utoken.
        /// </summary>
        /// <returns>The basedataquery.</returns>
        /// <param name="data">Data.</param>
        /// <param name="utoken">Utoken.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Basedataquery([FromBody]BasedataqueryReq data, [FromHeader(Name = "u-token")]string utoken)
        {
            if (data is null) {
                throw new ArgumentNullException(nameof(data));
            }

            logger.Trace($"basedataquery:{JsonConvert.SerializeObject(data)}");
            logger.Trace(utoken);
            if (data.Pagesize < 1) {
                data.Pagesize = 10;
            }
            var model = await _icApiService.BasedataQuery(data).ConfigureAwait(false);
            logger.Trace($"basedataqueryResult:{JsonConvert.SerializeObject(model)}");

            if (model.code == 0) {
                var list = JsonConvert.DeserializeObject<JArray>(model.content);
                return Ok(new { code = 0, model.pagecount, model.pageindex, model.pagesize, content = list });
            }
            //var bb = DateTime.Now;
            //var A= (bb.ToUniversalTime().Ticks - 621355968000000000) / 10000;
            //var B = DatetimeUtil.GetUnixTime(bb, Common.TimePrecision.Second);
            //return Ok(new { a = A, b = B });
            return Ok(model);
        }
        /// <summary>
        /// 查询特定产品清单
        /// </summary>
        /// <returns>The productlist.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Utoken.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Productlist([FromBody]ProductlistReq data, [FromHeader(Name = "u-token")]string token)
        {
            if (data is null) {
                throw new ArgumentNullException(nameof(data));
            }

            logger.Trace($"productlist:{JsonConvert.SerializeObject(data)}");

            var _cacheKey = _memcachedPre + Constant.BOOKING_PRODUCTLIST + "_" + data.Producttype + "_" + data.Sellerphone;

            var rsp = await _memcachedClient.GetValueAsync<Zmodel>(_cacheKey).ConfigureAwait(false);

            if (rsp == null) {
                var model = await _icApiService.Productlist(data).ConfigureAwait(false);
                logger.Trace($"productlistResult:{JsonConvert.SerializeObject(model)}");
                if (model.code == 0) {
                    await _memcachedClient.AddAsync(_cacheKey, model, 7200).ConfigureAwait(false);
                }
                rsp = model;
            }

            if (rsp.code == 0) {
                var list = JsonConvert.DeserializeObject<JArray>(rsp.content);
                return Ok(new { code = 0, content = list, imagurl = _imgUrl });
            }
            //var model = await _icApiService.Productlist(data).ConfigureAwait(false);
            //logger.Trace($"productlistResult:{JsonConvert.SerializeObject(model)}");
            //if (model.code == 0) {
            //    var list = JsonConvert.DeserializeObject<JArray>(model.content);
            //    return Ok(new { code = 0, content = list, imagurl = _imgUrl });
            //}
            return Ok(rsp);
        }

        /// <summary>
        /// 提货单退货
        /// </summary>
        /// <param name="data"></param>
        /// <param name="utoken"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GroupSellback([FromBody]GroupSellBackRequest data, [FromHeader(Name = "u-token")]string utoken)
        {
            logger.Trace($"GroupSellback:{JsonConvert.SerializeObject(data)}");
            var model = await _icApiService.GroupSellback(data).ConfigureAwait(false);
            logger.Trace($"GroupSellback:{JsonConvert.SerializeObject(model)}");
            
            return Ok(model);
        }

        /// <summary>
        /// 提货单退货
        /// </summary>
        /// <param name="data"></param>
        /// <param name="utoken"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> IcSellback([FromBody]IcSellBackRequest data, [FromHeader(Name = "u-token")]string utoken)
        {
            logger.Trace($"IcSellback:{JsonConvert.SerializeObject(data)}");
            var model = await _icApiService.IcSellback(data).ConfigureAwait(false);
            logger.Trace($"IcSellback:{JsonConvert.SerializeObject(model)}");
            
            return Ok(model);
        }

        /// <summary>
        /// 券卡销售
        /// </summary>
        /// <returns>The listsell.</returns>
        /// <param name="data">Data.</param>
        /// <param name="utoken">Utoken.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Listsell([FromBody]ListSellReq data, [FromHeader(Name = "u-token")]string utoken)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var mobile = MemberHelper.GetMobile(utoken);
            var employeeinfo = await _employeeService.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            if (employeeinfo != null) {
                data.Shopid = employeeinfo.StoreRelationId;
            }
            data.Sellerphone = mobile;
            logger.Trace($"listsell:{JsonConvert.SerializeObject(data)}");
            data.Customerinfo.Takerphone = Clearphonestr(data.Customerinfo.Takerphone);
            var model = await _icApiService.Listsell(data).ConfigureAwait(false);
            logger.Trace($"listsellResult:{JsonConvert.SerializeObject(model)}");
            return Ok(model);
        }
        private static string Clearphonestr(string phone)
        {
            if (phone.StartsWith('‭')) {
                if (phone.Length > 11) {
                    phone = phone.Substring(1, phone.Length - 1);
                }

            }
            if (phone.EndsWith("‬")) {
                if (phone.Length > 11) {
                    phone = phone.Substring(0, phone.Length - 1);
                }
            }
            return phone;
        }
        /// <summary>
        /// Liststatus the specified data and utoken.
        /// </summary>
        /// <returns>The liststatus.</returns>
        /// <param name="data">Data.</param>
        /// <param name="utoken">Utoken.</param>
        [HttpPost]
        [HttpOptions]
        [Route("[action]")]
        public async Task<IActionResult> Liststatus([FromBody]ListstatusReq data, [FromHeader(Name = "u-token")]string utoken)
        {
            logger.Trace($"liststatus:{JsonConvert.SerializeObject(data)}");
            var model = await _icApiService.Liststatus(data).ConfigureAwait(false);
            return Ok(model);
        }

        /// <summary>
        ///团购订货
        /// </summary>
        /// <returns>The grouporder.</returns>
        /// <param name="data">Data.</param>
        /// <param name="utoken">Utoken.</param>
        [HttpPost]
        //[HttpOptions]
        [Route("[action]")]
        public async Task<IActionResult> Grouporder([FromBody] GroupOrderReq data, [FromHeader(Name = "u-token")]string utoken)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            var mobile = MemberHelper.GetMobile(utoken);
            var employeeinfo = await _employeeService.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            if (employeeinfo != null) {
                data.Shopid = employeeinfo.StoreRelationId;
            }
            data.Sellerphone = mobile;
            data.Customerinfo.Takerphone = Clearphonestr(data.Customerinfo.Takerphone);
            logger.Trace($"Grouporder:{JsonConvert.SerializeObject(data)}");
            var model = await _icApiService.Grouporder(data).ConfigureAwait(false);
            logger.Trace($"GrouporderResult:{JsonConvert.SerializeObject(model)}");
            return Ok(model);

        }

        /// <summary>
        /// Getproductdetail the specified data and utoken.
        /// </summary>
        /// <returns>The getproductdetail.</returns>
        /// <param name="data">Data.</param>
        /// <param name="utoken">Utoken.</param>
        [HttpPost]
        //[HttpOptions]
        [Route("[action]")]
        public async Task<IActionResult> Getproductdetail([FromBody] ProductDetailReq data, [FromHeader(Name = "u-token")]string utoken)
        {
            Console.WriteLine($"{utoken}");
            logger.Trace($"Getproductdetail:{JsonConvert.SerializeObject(data)}");
            var model = await _icApiService.Productdetail(data).ConfigureAwait(false);
            logger.Trace($"Getproductdetailreuslt:{JsonConvert.SerializeObject(model)}");
            if (model.code == 0) {
                var list = JsonConvert.DeserializeObject<JObject>(model.content);
                return Ok(new { code = 0, content = list });
            }
            return Ok(model);
        }

        /// <summary>
        /// 团购订货编辑
        /// </summary>
        /// <returns>The groupordermodify.</returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GroupOrderModify([FromBody]GroupOrdermobifyRequest req, [FromHeader(Name = "u-token")]string utoken)
        {
            var mobile = MemberHelper.GetMobile(utoken);
            //var employeeinfo = await _employeeService.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            //if (employeeinfo != null)
            //{
            //    req.shopid = employeeinfo.StoreRelationId;
            //}
            logger.Trace($"Getproductdetail:{JsonConvert.SerializeObject(req)}");

            var model = await _icApiService.Groupordermodify(req).ConfigureAwait(false);
            return Ok(model);
        }

        /// <summary>
        /// 团购订货退货
        /// </summary>
        /// <param name="req"></param>
        /// <param name="utoken"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GroupOrderBack([FromBody]GroupOrderBackRequest req, [FromHeader(Name = "u-token")]string utoken)
        {
            var mobile = MemberHelper.GetMobile(utoken);
            //var employeeinfo = await _employeeService.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            //if (employeeinfo != null)
            //{
            //    req.shopid = employeeinfo.StoreRelationId;
            //}
            logger.Trace($"Getproductdetail:{JsonConvert.SerializeObject(req)}");

            var model = await _icApiService.GroupOrderlback(req).ConfigureAwait(false);
            return Ok(model);
        }


        /// <summary>
        /// 团购订单删除
        /// </summary>
        /// <returns>The grouporderdelete.</returns>
        /// <param name="req">Req.</param>
        /// <param name="utoken">Utoken.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GroupOrderDelete([FromBody]GrouporderdeleteReq req, [FromHeader(Name = "u-token")]string utoken)
        {
            var mobile = MemberHelper.GetMobile(utoken);
            var employeeinfo = await _employeeService.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            if (employeeinfo == null) {
                logger.Trace($"Getproductdetail:bucunzai");
            }
            logger.Trace($"grouporderdelete:{JsonConvert.SerializeObject(req)}");
            var model = await _icApiService.Grouporderdelete(req).ConfigureAwait(false);
            return Ok(model);
        }

        /// <summary>
        /// 单据清单查询
        /// </summary>
        /// <returns>The listquery.</returns>
        /// <param name="data">Data.</param>
        /// <param name="utoken">Utoken.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> ListQuery([FromBody] ListQueryReq data, [FromHeader(Name = "u-token")]string utoken)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }
            if (data.Pageindex < 1) { data.Pageindex = 1; }
            if (data.Pagesize < 1) {
                data.Pagesize = 10;
            }
            //return Ok(new { code = 999, msg = "抱歉，接口暂时关闭！" });
            logger.Trace($"listquery:{JsonConvert.SerializeObject(data)}");
            var mobile = MemberHelper.GetMobile(utoken);
            data.Sellerphone = mobile;
            data.Sellername = "";
            var model = await _icApiService.Listquery(data).ConfigureAwait(false);
            logger.Trace($"listquery,rsp:{JsonConvert.SerializeObject(model)}");
            if (model.code == 0) {
                var list = JsonConvert.DeserializeObject<JArray>(model.content);
                return Ok(new { code = 0, model.pagecount, model.pageindex, model.pagesize, content = list });
            }
            return Ok(model);
        }

        /// <summary>
        /// 单据明细查询
        /// </summary>
        /// <returns>The listdetail.</returns>
        /// <param name="data">Data.</param>
        /// <param name="utoken">Utoken.</param>
        [HttpPost]
        //[HttpOptions]
        [Route("[action]")]
        public async Task<IActionResult> ListDetail([FromBody] ListDetailReq data, [FromHeader(Name = "u-token")]string utoken)
        {
            logger.Trace($"listdetail:{JsonConvert.SerializeObject(data)}");
            var model = await _icApiService.Listdetail(data).ConfigureAwait(false);
            logger.Trace($"listdetailresult:{ JsonConvert.SerializeObject(model)}");
            if (model.code == 0) {
                var list = JsonConvert.DeserializeObject<JObject>(model.content);
                return Ok(new { code = 0, content = list });
            }
            return Ok(model);
        }

        /// <summary>
        /// 开具发票明细
        /// </summary>
        /// <returns>The invoice.</returns>
        /// <param name="data">Data.</param>
        /// <param name="utoken">Utoken.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Invoice([FromBody] InvoiceReq data, [FromHeader(Name = "u-token")]string utoken)
        {
            var mobile = MemberHelper.GetMobile(utoken);

            var model = await _icApiService.Invoice(data).ConfigureAwait(false);
            logger.Trace($"invoice:{ JsonConvert.SerializeObject(model)}");
            if (model.code == 0) {
                var list = JsonConvert.DeserializeObject<JObject>(model.content);
                return Ok(new { code = 0, content = list });
            }
            return Ok(model);
        }
        /// <summary>
        /// 发票查询
        /// </summary>
        /// <returns>The invoicequery.</returns>
        /// <param name="data">Data.</param>
        /// <param name="utoken">Utoken.</param>
        [HttpPost]
        // [HttpOptions]
        [Route("[action]")]
        public async Task<IActionResult> Invoicequery([FromBody] InvoiceQueryReq data, [FromHeader(Name = "u-token")]string utoken)
        {
            var mobile = MemberHelper.GetMobile(utoken);
            data.Sellerphone = mobile;
            var model = await _icApiService.Invoicequery(data).ConfigureAwait(false);
            logger.Trace($"invoicequery:{ JsonConvert.SerializeObject(model)}");
            if (model.code == 0) {
                var list = JsonConvert.DeserializeObject<JObject>(model.content);
                return Ok(new { code = 0, content = list });
            }
            return Ok(model);
        }
    }
}
